package com.example.customview.gradienttext

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import android.os.Build
import android.util.AttributeSet
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatTextView
import java.util.jar.Attributes

/**
 * 渐变的textview
 */
class GradientView @JvmOverloads constructor(context:Context,attrs: AttributeSet?=null,defaultStyle:Int = 0) :AppCompatTextView(context,attrs,defaultStyle) {

    private  var mOriginalPaint: Paint = Paint()
    private  var mGradientPaint: Paint = Paint()
    private var progress = 0.0f
    init {
        mOriginalPaint.textSize = textSize
        mOriginalPaint.style = Paint.Style.FILL
        mOriginalPaint.isAntiAlias = true

        mGradientPaint.textSize = textSize
        mGradientPaint.style = Paint.Style.FILL
        mGradientPaint.isAntiAlias = true
        mGradientPaint.color = Color.GREEN


    }

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val startProgress = (width*progress).toInt()
        drawText(canvas,mGradientPaint,0,startProgress)
        drawText(canvas,mOriginalPaint,startProgress,width)


    }

    private fun drawText(canvas: Canvas, paint: Paint,start:Int,end:Int){
        canvas.save()
        val content = text.toString()
        val clipRect = Rect(start,0,end,height)
        canvas.clipRect(clipRect)
        val fontMetrics = paint.fontMetrics
        val dy = (fontMetrics?.descent!! - fontMetrics.ascent)/2- fontMetrics.descent
        val baseLine = height / 2 + dy
        val rect = Rect()
        paint.getTextBounds(content,0,content.length,rect)
        val startX = width/2 -rect.width()/2
        canvas.drawText(content, startX.toFloat(),baseLine,paint)
        canvas.restore()
    }

    fun setProgress(progress:Float){
        this.progress = progress
        invalidate()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

}